import patchVnode from "./patchVnode";
import createElement from "./createElement";

function checkSameVnode(oldVnode, newVnode) {
    return (oldVnode.sel == newVnode.sel && oldVnode.key == newVnode.key);
}

export default function updateChild(parentElm, oldCh, newCh) {
    // 旧前
    let oldStartIndex = 0;
    // 旧后
    let oldEndIndex = 0;
    // 新前
    let newStartIndex = oldCh.length - 1;
    // 新后
    let newEndIndex = newCh.length - 1;
    // 旧前节点
    let oldStartVnode = oldCh[0];
    // 旧后
    let oldEndVnode = oldCh[oldEndIndex];
    // 新前
    let newStartVnode = newCh[0];
    // 新后
    let newEndVnode = newCh[newEndIndex];

    while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) {
        // 新前和旧前
        if (checkSameVnode(oldStartVnode, newStartIndex)) {
            patchVnode(oldStartVnode, newStartVnode);
            oldStartVnode = oldCh[++oldStartIndex];
            newStartVnode = newCh[++newStartIndex];
        } else if (checkSameVnode(oldEndVnode, newEndVnode)) {
            // 新后和旧后
            patchVnode(oldEndVnode, newEndVnode);
            oldEndVnode = oldCh[--oldEndIndex];
            newEndVnode = newCh[--newEndIndex];
        } else if (checkSameVnode(oldStartVnode, newEndVnode)) {
            // 新后和旧前
            patchVnode(oldStartVnode, newEndVnode);

            oldStartVnode = oldCh[++oldStartIndex];
            newEndVnode = newCh[--newEndIndex];
        }
    }
}